package com.xg.te.plugin;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.jarveis.frame.io.HttpUtil;
import com.jarveis.frame.io.HttpUtil.HttpMethod;
import com.jarveis.frame.lang.StringUtil;
import com.jarveis.frame.util.JsonUtil;
import com.jarveis.frame.util.Pager;
import com.jarveis.frame.util.Result;
import com.xg.te.core.WebsiteStore;
import com.xg.te.core.bean.WebsiteBean;

/**
 * @desc WebService数据插件
 * @author liuguojun
 * @date 2015-05-24
 */
public class WebServicePlugin implements Plugin {

	private static final Logger logger = Logger
			.getLogger(WebServicePlugin.class);

	public Map execute(JSONObject jsonObj) {
		Map reMap = null;
		try {
			// 服务接口
			String dataLink = jsonObj.getString("data");
			if (StringUtil.isEmpty(dataLink)) {
				throw new Exception("parameter data is empty");
			}
			
			// 服务地址
			String websitetCode = jsonObj.getString("websiteCode");
			if (!StringUtil.isEmpty(websitetCode)) {
				WebsiteBean website = WebsiteStore.get(websitetCode);
				String webService = website.getConstantValue("webService");
				dataLink = webService + dataLink;
			}
			
			// 参数
			String queueValue = jsonObj.getString("queueValue");
			if (!StringUtil.isEmpty(queueValue)) {
				dataLink = dataLink.replace("{queueValue}", queueValue);
			}

			String params = dataLink.substring(dataLink.indexOf("?") + 1);
			String resultStr = connect(dataLink);
			Result result = (Result) JsonUtil.parse(resultStr);
			if (result.isSuccess()) {
				Object data = result.getData();
				if (data instanceof Pager) {
					reMap = convert((Pager) data);
					reMap.put("params", params);
				} else if (data instanceof Map) {
					reMap = (Map) data;
					reMap.put("params", params);
				}
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}

		return reMap;
	}

	/**
	 * 获取根节点
	 * 
	 * @param file
	 * @return
	 */
	private String connect(String uri) {
		String result = "";

		HttpUtil http = new HttpUtil(uri, HttpMethod.GET);
		if (http.doRequest()) {
			result = new String(http.getRespData());
		}

		return result;
	}

	/**
	 * 数据转换
	 * 
	 * @param pager
	 * @return
	 */
	private Map<String, Object> convert(Pager pager) {
		Map<String, Object> map = new HashMap<String, Object>(9);

		map.put("pagesize", pager.getPagesize());
		map.put("curpage", pager.getCurpage());
		map.put("sum", pager.getSum());
		map.put("pages", pager.getPages());
		map.put("start", pager.getStart());
		map.put("end", pager.getEnd());
		map.put("data", pager.getData());
		map.put("sort", pager.getOrder());
		map.put("order", pager.getSort());

		return map;
	}

}
